﻿<%@ WebHandler Language="C#" Class="ZSMaterialLackInfoReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 装配试车厂--缺料进度查询报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2023.4.18
 **/

public class ZSMaterialLackInfoReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    case "getContainer":
                        r = getContainer(jObject);//查看进度弹窗
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT t.*,
       MIN(cci.plannedcompletiondate) plannedcompletiondate,
       CASE WHEN MIN(cci.plannedcompletiondate) IS NULL THEN ''
            WHEN t.startdate - TRUNC(MIN(cci.plannedcompletiondate)) > 3 THEN ''
            WHEN t.startdate - TRUNC(MIN(cci.plannedcompletiondate)) <= 3 AND t.startdate - TRUNC(MIN(cci.plannedcompletiondate)) >= 0 THEN 'warning'
            WHEN t.startdate - TRUNC(MIN(cci.plannedcompletiondate)) < 0 THEN 'danger'
       END status
FROM (
    SELECT t.aufnr mfgordername,u.attributevalue engineno,
           t.auart ordertype,f.factoryname uesfactoryname,--使用分厂
           mfg.qty mfgqty,t.zmodel productfamilyname,
           t.berid militarytype,
           TO_DATE(t.gstrp,'yyyy/mm/dd') startdate,
           TO_DATE(t.gltrp,'yyyy/mm/dd') enddate,
           t.posnr seq,
           t.idnrk productname,t.idnrk_t productdesc,f2.factoryname factoryname,f2.factorycode,
           ROUND(t.bdmng,0) qty,--需求数量
           ROUND(t.labst_q,0) lackqty--缺料数量
    FROM t_ddqlt t
    INNER JOIN mfgorder mfg ON mfg.mfgordername = t.aufnr 
    LEFT JOIN userattribute u ON u.parentid = mfg.mfgorderid AND u.userattributename = '发动机'
    LEFT JOIN mes_factory_mapping f ON f.factorycode = t.userunit --使用分厂
    LEFT JOIN mes_factory_mapping f2 ON f2.factorycode = t.fevor --主制分厂
    WHERE 1=1 ";
        //件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND t.idnrk = '{0}'", jObject["productname"].ToString());
        }
        //发动机号
        if (jObject["engineno"] != null && jObject["engineno"].ToString() != "")
        {
            sql += string.Format(" AND u.attributevalue = '{0}'", jObject["engineno"].ToString());
        }
        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND t.aufnr = '{0}'", jObject["mfgordername"].ToString());
        }
        //使用分厂
        if (jObject["uesfactoryname"] != null && jObject["uesfactoryname"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryname LIKE '%{0}%'", jObject["uesfactoryname"].ToString());
        }
        //主制分厂
        if (jObject["fevor"] != null && jObject["fevor"].ToString() != "")
        {
            sql += string.Format(" AND f2.factoryname LIKE '%{0}%'", jObject["fevor"].ToString());
        }
        //计划开始
        if (jObject["startdate"] != null && jObject["startdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["startdate"].ToString());
            sql += string.Format(" AND TO_DATE(t.gstrp,'yyyy/mm/dd') >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
            sql += string.Format(" AND TO_DATE(t.gstrp,'yyyy/mm/dd') <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
        }
        //计划完成
        if (jObject["enddate"] != null && jObject["enddate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["enddate"].ToString());
            sql += string.Format(" AND TO_DATE(t.gltrp,'yyyy/mm/dd') >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
            sql += string.Format(" AND TO_DATE(t.gltrp,'yyyy/mm/dd') <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
        }
        sql += @"
) t
INNER JOIN containercurrentinfo cci ON cci.mfgordername = t.mfgordername
GROUP BY t.mfgordername,t.engineno,t.ordertype,t.uesfactoryname,t.mfgqty,t.productfamilyname,t.militarytype,t.startdate,
         t.enddate,t.seq,t.productname,t.productdesc,t.factoryname,t.factorycode,t.qty,t.lackqty";
        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getContainer(JObject jObject)
    {
        string sql = @"
SELECT cci.productname,cci.productdescription,f.factoryname,cci.mfgordername,cci.containername,cci.qty,cci.plannedstartdate,cci.plannedcompletiondate
FROM containercurrentinfo cci
LEFT JOIN mes_factory_mapping f ON f.factoryid = cci.originalfactoryid
WHERE f.factorycode = '{0}' AND cci.productname = '{1}'
ORDER BY cci.plannedcompletiondate";
        sql = string.Format(sql, jObject["factorycode"].ToString(), jObject["productname"].ToString());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dtResult.Columns.Remove("status");
        dtResult.Columns.Remove("factorycode");
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["engineno"].Caption = "发动机号";
        dtResult.Columns["ordertype"].Caption = "订单类型";
        dtResult.Columns["uesfactoryname"].Caption = "使用分厂";
        dtResult.Columns["mfgqty"].Caption = "订单数量";
        dtResult.Columns["productfamilyname"].Caption = "机型";
        dtResult.Columns["militarytype"].Caption = "军种";
        dtResult.Columns["startdate"].Caption = "计划开始";
        dtResult.Columns["enddate"].Caption = "计划结束";
        dtResult.Columns["seq"].Caption = "序号";
        dtResult.Columns["productname"].Caption = "组件料号";
        dtResult.Columns["productdesc"].Caption = "组件名称";
        dtResult.Columns["factoryname"].Caption = "主制单位";
        dtResult.Columns["plannedcompletiondate"].Caption = "批次计划完成时间";
        dtResult.Columns["qty"].Caption = "需求数量";
        dtResult.Columns["lackqty"].Caption = "缺料数量";
        ExportHelper.ExportExcel(dtResult, "缺料进度查询报表");
    }
}